package com.epi.two;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

/**
 * 员工类，支持序列化
 * @author dxy
 * @version 1.0
 */
@Slf4j
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;

    private int id;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public Employee(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    // Getter 和 Setter 方法

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", age=" + age +
            ", salary=" + salary +
            '}';
    }

    private Object readResolve() {
        log.info("read resolve");
        if (this.id == 101) {
            return DummyEmployeeHolder.INSTANCE;
        }
        return this;
    }
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        log.info("read object");
        in.defaultReadObject(); // 让 JVM 自动处理基本字段
        // 或者自己手动读取字段，否则字段还是默认值  ————》Externalizable
//        this.age = in.readInt();
        this.age = 1000000;     // 修改 age 字段
    }


    // 内部静态类用于持有单例对象
    private static class DummyEmployeeHolder {
        private static final Employee INSTANCE = new Employee(101, "Unknown", 0, 0.0);
    }
}
